<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-warn"></i>&nbsp;&nbsp;一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="table_btn">
                <el-button icon="el-icon-refresh" @click="refresh" :loading="buttonLoading">刷新</el-button>
                <el-button type="success" icon="el-icon-lx-roundadd" @click="addVisible = true">添加</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="allDelete()">批量删除</el-button>
                <el-button type="primary" icon="el-icon-sort" @click="handleSort">排序</el-button>
            </div>
            <div>
                <el-table
                        :data="tableData"
                        style="width: 100%;margin-bottom: 20px;"
                        row-key="id"
                        border
                        :default-expand-all="false"
                        @selection-change="handleSelectionChange"
                        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">

                    <el-table-column
                            el-table-column
                            type="selection"
                            width="50">
                    </el-table-column>

                    <el-table-column
                            prop="title"
                            label="标题">
                    </el-table-column>

                    <el-table-column
                            prop="id"
                            label="ID"
                            width="100">
                    </el-table-column>

                    <el-table-column
                            prop="icon"
                            label="图标"
                            width="120">
                        <template slot-scope="scope">
                            <i v-if="scope.row.icon" class="i_fontsize" :class="scope.row.icon"></i>
                        </template>
                    </el-table-column>

                    <el-table-column
                            prop="name"
                            label="规则">
                    </el-table-column>

                    <el-table-column
                            prop="weigh"
                            label="排序"
                            width="120">

                        <template slot-scope="scope">
                            <el-input type="number" size="small" v-model="scope.row.weigh"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column
                            prop="status"
                            label="状态"
                            width="120">
                        <template slot-scope="scope">
                            <el-tag
                                    :type="scope.row.status == 1 ? 'success' : 'danger'"
                                    disable-transitions>{{scope.row.status == 1 ? "正常" : "禁用"}}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="200">
                        <template slot-scope="scope">
                            <el-button
                                    size="mini"
                                    icon="el-icon-edit"
                                    type="primary"
                                    @click="showEdit(scope.$index, scope.row)">
                                编辑
                            </el-button>
                            <el-button
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.$index, scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <!--添加规则-->
        <el-dialog title="添加规则" :visible.sync="addVisible" width="35%">

            <el-form :model="form" :rules="rules" ref="form" label-width="100px">

                <el-form-item label="菜单">
                    <el-switch v-model="form.ismenu"
                               active-text="是"
                               inactive-text="否"
                               :active-value="1"
                               :inactive-value="0"
                    ></el-switch>
                </el-form-item>

                <el-form-item label="父级" prop="pid">

                    <el-select v-model="form.pid" size="medium" placeholder="请选择父级">
                        <el-option
                                v-for="item in ruleOpt"
                                :key="item.id"
                                :label="item.title_show"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="规则" prop="name">
                    <el-input v-model="form.name" placeholder="请输入规则"></el-input>
                </el-form-item>

                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入标题"></el-input>
                </el-form-item>

                <el-form-item label="图标" prop="icon">
                    <icon-picker v-model="form.icon"></icon-picker>
                </el-form-item>

                <el-form-item label="排序" prop="weigh">
                    <el-input v-model="form.weigh" placeholder="请输入排序"></el-input>
                </el-form-item>


                <el-form-item label="规则条件" prop="condition">
                    <el-input type="textarea"
                              placeholder="请输入规则条件"
                              :rows="2"
                              v-model="form.condition">
                    </el-input>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea"
                              placeholder="请输入备注"
                              :rows="2"
                              v-model="form.remark">
                    </el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="form.status"
                               active-text="正常"
                               inactive-text="隐藏"
                               :active-value="1"
                               :inactive-value="0"
                    ></el-switch>
                </el-form-item>


                <el-form-item>
                    <el-button type="primary" @click="handleAdd('form')" :loading="buttonLoading">立即创建</el-button>
                    <el-button @click="resetForm('form')">重置</el-button>
                </el-form-item>

            </el-form>
        </el-dialog>

        <!--编辑规则-->
        <el-dialog title="编辑规则" :visible.sync="editVisible" width="35%">

            <el-form :model="editForm" :rules="editRules" ref="edit-form" label-width="100px">

                <el-form-item label="菜单">
                    <el-switch v-model="editForm.ismenu"
                               active-text="是"
                               inactive-text="否"
                               :active-value="1"
                               :inactive-value="0"
                    ></el-switch>
                </el-form-item>

                <el-form-item label="父级" prop="pid">

                    <el-select v-model="editForm.pid" size="medium" placeholder="请选择父级">
                        <el-option
                                v-for="item in editRuleOpt"
                                :key="item.id"
                                :label="item.title_show"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="规则" prop="name">
                    <el-input v-model="editForm.name" placeholder="请输入规则"></el-input>
                </el-form-item>

                <el-form-item label="标题" prop="title">
                    <el-input v-model="editForm.title" placeholder="请输入标题"></el-input>
                </el-form-item>

                <el-form-item label="图标" prop="icon">
                    <icon-picker v-model="editForm.icon"></icon-picker>
                </el-form-item>

                <el-form-item label="排序" prop="weigh">
                    <el-input v-model="editForm.weigh" placeholder="请输入排序"></el-input>
                </el-form-item>


                <el-form-item label="规则条件" prop="condition">
                    <el-input type="textarea"
                              placeholder="请输入规则条件"
                              :rows="2"
                              v-model="editForm.condition">
                    </el-input>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea"
                              placeholder="请输入备注"
                              :rows="2"
                              v-model="editForm.remark">
                    </el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="editForm.status"
                               active-text="正常"
                               inactive-text="隐藏"
                               :active-value="1"
                               :inactive-value="0"
                    ></el-switch>
                </el-form-item>


                <el-form-item>
                    <el-button type="primary" @click="handleEdit('edit-form')" :loading="buttonLoading">确 定</el-button>
                    <el-button @click="resetForm('edit-form')">重置</el-button>
                </el-form-item>

            </el-form>
        </el-dialog>

    </div>
</template>
<script>

    import utils from "@/utils/function"

    const {request} = utils

    export default {
        data() {
            let addRules = {
                pid: [
                    {required: true, message: '请选择父级', trigger: 'change'}
                ],
                name: [
                    {required: true, message: '请输入规则', trigger: 'blur'},
                ],
                title: [
                    {required: true, message: '请输入标题', trigger: 'blur'},
                    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                ],
                icon: [
                    {required: true, message: '请输入图标', trigger: 'blur'},
                ],
                weigh: [
                    {required: true, message: '请输入排序', trigger: 'blur'},
                ]
            }
            return {
                multipleSelection: [],           //列表中checkbox选中的值
                tableData: [],
                rules: addRules,
                editRules: addRules,
                addVisible: false,        //添加面板显示
                editVisible: false,
                ruleOpt: [],     //角色列表选项
                editRuleOpt: [],
                buttonLoading: false,        //按钮加载
                form: {
                    ismenu: 0,
                    pid: 0,
                    title: '',
                    icon: '',
                    weigh: 50,
                    condition: '',
                    remark: '',
                    name: '',
                    status: 0
                },
                editForm: {
                    id: 0,
                    ismenu: 0,
                    pid: 0,
                    title: '',
                    icon: '',
                    weigh: 50,
                    condition: '',
                    remark: '',
                    name: '',
                    status: 0
                },

            }
        },
        methods: {
            delete(ids) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (_.isNumber(ids)) {
                        ids = [ids]
                    }
                    if (!_.isArray(ids)) {
                        return false;
                    }

                    request.post("/system/auth/delete-menu", {ids}).then(response => {

                        console.log(response);
                        let {code, data, msg} = response
                        if (code === 0) {
                            this.getRuleTree()
                            this.getRuleOpt()
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        } else {
                            this.$message.error(msg);
                        }
                    }).catch(error => {
                        console.log(error);
                    });

                }).catch((error) => {
                    console.log(error);
                    this.$message({
                        type: 'info',
                        message: '删除失败，请重试!'
                    });
                });
            },
            handleSelectionChange(val) {                //列表checkbox选中事件
                this.multipleSelection = val;
            },
            allDelete() {                        //删除多条
                if (this.multipleSelection.length < 1) {
                    this.$message.error('选择要删除的内容');
                    return false
                }
                this.delete(this.multipleSelection.map(value => value.id))
            },
            handleDelete(index, row) {            //删除一条
                this.delete(row.id);
            },
            handleAdd(form) {            //添加操作
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true
                        request.post("/system/auth/add-menu", this.form).then(response => {
                            this.buttonLoading = false
                            let {code, data, msg} = response
                            if (code === 0) {
                                this.$message.success(msg);
                                this.addVisible = false;
                                this.getRuleTree();
                                this.getRuleOpt();
                                this.resetForm(form);
                            } else {
                                this.$message.error(msg);
                            }
                        }).catch(error => {
                            console.log(error);
                        });

                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            handleSort() {          //排序
                const getSortData = function (arr) {
                    let obj = {};
                    let result = {};
                    while (obj = arr.shift()) {
                        if (!obj.id || !obj.weigh) {
                            break;
                        }
                        result[obj.id] = obj.weigh + ""
                        if (obj.children && obj.children.length && obj.children.length > 0) {
                            result = Object.assign(result, getSortData(obj.children))
                        }
                    }

                    return result;
                }

                let sorts = getSortData(_.cloneDeep(this.tableData));
                request.loading().post("/system/auth/menu-sort", {sorts: sorts}).then(response => {
                    let {code, data, msg} = response
                    if (code === 0) {

                        this.getRuleTree();
                        this.$message({
                            type: 'success',
                            message: msg
                        });
                    } else {
                        this.$message.error(msg);
                    }
                })
            },
            showEdit(index, row) {              //显示编辑界面

                request.loading().get('/system/auth/edit-menu', {id: row.id}).then(response => {
                    let {
                        code,
                        data: {menu: {id, type, pid, name, title, icon, condition, remark, ismenu, weigh, status}, parentList},
                        msg
                    } = response
                    if (code === 0) {
                        this.editVisible = true
                        this.editRuleOpt = parentList || []
                        this.editForm.id = id || 0
                        this.editForm.ismenu = ismenu || 0
                        this.editForm.pid = pid || 0
                        this.editForm.title = title || ''
                        this.editForm.icon = icon || ''
                        this.editForm.weigh = weigh || 50
                        this.editForm.condition = condition || ''
                        this.editForm.remark = remark || ''
                        this.editForm.name = name || ''
                        this.editForm.status = status || 0
                    } else {
                        this.$message.error(msg);
                    }
                })

            },
            handleEdit(form) {                       //提交编辑

                this.$refs[form].validate((valid) => {
                    if (!valid) {
                        console.log('error submit!!');
                        return false;
                    }
                    this.buttonLoading = true

                    request.post("/system/auth/edit-menu", this.editForm).then(response => {
                        this.buttonLoading = false
                        let {code, data, msg} = response
                        if (code === 0) {
                            this.editVisible = false
                            this.$message.success(msg);
                            this.getRuleTree()
                            this.getRuleOpt()
                            this.resetForm(form)
                        } else {
                            this.$message.error(msg);
                        }
                    }).catch(error => {
                        console.log(error);
                    });
                })


            },

            getRuleTree() {          //获取列表数据
                return request.loading().get("/system/auth/menu-list").then(response => {
                    let {code, data: {list}, msg} = response
                    if (code === 0) {


                        if (_.isArray(list) && list.length > 0) {
                            this.tableData = list
                        } else {
                            this.tableData = []
                        }

                    } else {
                        this.$message.error(msg);
                    }
                    return response
                })
            },

            getRuleOpt() {       //角色列表选项
                request.loading().get("/system/auth/add-menu").then(response => {
                    let {code, data: {parentList}, msg} = response
                    if (code === 0) {
                        this.ruleOpt = parentList
                    } else {
                        this.$message.error(msg);
                    }
                    return response
                })
            },

            refresh() {          //刷新操作
                this.buttonLoading = true
                this.getRuleTree().then(response => {
                    this.buttonLoading = false
                });
            },

            resetForm(formName) {        //重置表单
                this.$refs[formName].resetFields();
            },
        },

        created() {
            this.getRuleTree();
            this.getRuleOpt();
        }
    }
</script>
<style>
    .i_fontsize {
        font-size: 1.5em
    }
</style>
